package controllers

import (
	"priceApi/spider"
	"strings"
	//"encoding/json"

	"priceApi/models"

	"strconv"
	"time"

	"github.com/astaxie/beego"

	//"github.com/astaxie/beego"

	"priceApi/utils"

	"github.com/astaxie/beego/orm"
)

type MainController struct {
	beego.Controller
}

type GetPriceController struct {
	beego.Controller
}

type GetRateController struct {
	beego.Controller
}

type GetCoinriseController struct {
	beego.Controller
}

type TestController struct {
	beego.Controller
}
type MytestController struct {
	beego.Controller
}
type GetV2PriceController struct {
	beego.Controller
}
type GetV2CoinriseController struct {
	beego.Controller
}
type GetV3PriceController struct {
	beego.Controller
}

type GetV3CoinriseController struct {
	beego.Controller
}

func (c *MytestController) Get() {

	c.Data["Website"] = GetRateUSDT()
	c.Data["Email"] = "222"
	c.TplName = "my.tpl"
}

func GetRateUSDT() float64 {

	o1 := orm.NewOrm()
	var rate models.Rate
	o1.QueryTable("Rate").OrderBy("-Created").One(&rate)
	return rate.Rate
}

func (c *MainController) Get() {

	c.Data["Website"] = GetRateUSDT()
	c.Data["Email"] = "222"
	c.TplName = "index.tpl"
}

//SELECT * FROM `price` WHERE `Symbol`="BTC" AND Created < 1520228966 ORDER BY `Created` DESC

type TypeBuySell struct {
	Type int
	Buy  float64
	Sell float64
}

func GetDataFromMydql(symbol string) TypeBuySell {
	Type := 3
	var data TypeBuySell
	var price models.Price

	o1 := orm.NewOrm()

	count, _ := o1.QueryTable("Price").Count()

	o1.QueryTable("Price").Filter("Id__gt", count-50).Filter("Symbol", symbol).Filter("Type", Type).OrderBy("-Created").One(&price)
	if price.Created+600 < int(time.Now().Unix()) {
		Type = 2
		go utils.SendToMail("GetDataFromMydql", symbol+"10分钟数据未刷新")
	}
	data.Buy = price.Buy
	data.Sell = price.Sell
	data.Type = Type

	return data
}

func (c *GetV2PriceController) Get() {
	key := "price"

	symbol := strings.ToUpper(c.GetString(":id"))

	if symbol == "BTC" || symbol == "ETH" || symbol == "LTC" || symbol == "URMB" {
		key = symbol
	}
	data10, err0 := utils.GetRedisByKey("v2" + key)

	if err0 == nil {
		c.Data["json"] = data10
		c.ServeJSON()
		return
	}
	//fmt.Println("new", key)

	data := map[string]interface{}{
		"Code": 0,
		"Data": "",
		"Msg":  "",
	}
	data0 := map[string]interface{}{}

	if symbol == "BTC" || symbol == "ETH" || symbol == "LTC" || symbol == "URMB" {
		price := GetDataFromMydql(symbol)

		data0[symbol] = price

	} else {
		symbols := utils.GetSymbolsByConf()

		for _, v := range symbols {
			price := GetDataFromMydql(v)

			data0[v] = price
		}

	}
	beego.Debug(data0)
	data["Data"] = data0
	utils.SetRedisBuyKey("v2"+key, data)

	c.Data["json"] = data
	c.ServeJSON()
}

func (c *GetPriceController) Get() {
	key := "price"
	symbol := strings.ToUpper(c.GetString(":id"))

	if symbol == "BTC" || symbol == "ETH" || symbol == "LTC" {
		key = symbol
	}
	data10, err0 := utils.GetRedisByKey(key)

	if err0 == nil {
		c.Data["json"] = data10
		c.ServeJSON()
		return
	}
	//fmt.Println("new", key)
	over := -0.0032
	data := map[string]interface{}{
		"Code": 0,
		"Data": "",
		"Msg":  "",
	}
	data0 := map[string]interface{}{}

	if symbol == "BTC" || symbol == "ETH" || symbol == "LTC" || symbol == "BCH" {
		price := GetDataFromMydql(symbol)
		if price.Type == 2 {
			Price, err := spider.GetGateioPrice()
			if err != nil {
				price.Type = 1
			} else {
				price.Buy = Price[symbol]
				price.Sell = Price[symbol]
			}
		}
		if symbol == "BTC" {
			price.Buy = MyRound(price.Buy * (1 + over))
			price.Sell = MyRound(price.Sell * (1 + over))
		} else {
			price.Buy = MyRound(price.Buy * (1 + 0))
			price.Sell = MyRound(price.Sell * (1 - 0))
		}

		data0[symbol] = price

	} else {
		symbols := utils.GetSymbolsByConf()
		Price := make(map[string]float64)
		var err12 error
		var i = 0
		for _, v := range symbols {
			price := GetDataFromMydql(v)
			if price.Type == 2 {
				if i == 0 {
					Price, err12 = spider.GetGateioPrice()
					i = 1
				}

				if err12 != nil {
					price.Type = 1
				} else {
					price.Buy = Price[v]
					price.Sell = Price[v]
				}
			}
			if v == "BTC" {
				price.Buy = MyRound(price.Buy * (1 + over))
				price.Sell = MyRound(price.Sell * (1 + over))
			} else {
				price.Buy = MyRound(price.Buy * (1 + 0))
				price.Sell = MyRound(price.Sell * (1 - 0))
			}
			data0[v] = price
		}

	}
	beego.Debug(data0)
	data["Data"] = data0
	utils.SetRedisBuyKey(key, data)

	c.Data["json"] = data
	c.ServeJSON()
}

func (c *GetRateController) Get() {
	key := "rate"
	data0, err0 := utils.GetRedisByKey(key)

	if err0 == nil {
		c.Data["json"] = data0
		c.ServeJSON()
		return
	}
	//fmt.Println("new", key)
	data := map[string]interface{}{}
	data["rate"] = GetRateUSDT()

	utils.SetRedisBuyKey(key, data)
	c.Data["json"] = data
	c.ServeJSON()
}

func GetRiseBy24H(symbol string, price float64, Type int) (float64, int) {
	o1 := orm.NewOrm()
	var price_1 models.Price
	count, _ := o1.QueryTable("Price").Count()
	o1.QueryTable("Price").Filter("Id__gt", count-15000).Filter("Symbol", symbol).Filter("Type", Type).Filter("Created__lte", int(time.Now().Unix())-24*60*60).OrderBy("-Created").One(&price_1)
	var rise float64
	var rise_mark int
	prise_buy_sell := (price_1.Buy + price_1.Sell) / 2
	if prise_buy_sell <= 0 {
		rise = 0
		rise_mark = 1
		return rise, rise_mark
	}
	if price >= prise_buy_sell {
		rise_mark = 1

		rise = MyRound(100 * (price - prise_buy_sell) / prise_buy_sell)
	} else {
		rise_mark = 0
		rise = MyRound(100 * (prise_buy_sell - price) / prise_buy_sell)
	}

	return rise, rise_mark
}

func (c *GetCoinriseController) Get() {
	key := "coinrise"
	data0, err0 := utils.GetRedisByKey(key)
	//fmt.Println(data0, err0)

	if err0 == nil {
		c.Data["json"] = data0
		c.ServeJSON()
		return
	}
	//fmt.Println("new", key)
	symbols := utils.GetSymbolsByConf()
	over := 0.0
	data := map[string]interface{}{}

	for i := 0; i < len(symbols); i++ {
		data0 := map[string]interface{}{
			"price":     0.0,
			"rise":      0.0,
			"rise_mark": 0,
		}
		price := *new(TypeBuySell)
		price = GetDataFromMydql(symbols[i])
		v := MyRound((1 + over) * (price.Buy + price.Sell) / 2)
		data0["price"] = v
		data0["rise"], data0["rise_mark"] = GetRiseBy24H(symbols[i], v, price.Type)
		data[symbols[i]] = data0
	}

	//data["UWN"] = GetErc20CoinRise("UWN")

	utils.SetRedisBuyKey(key, data)

	c.Data["json"] = data
	c.ServeJSON()
}

func (c *GetV2CoinriseController) Get() {
	key := "coinrise"
	data0, err0 := utils.GetRedisByKey("v2" + key)
	//fmt.Println(data0, err0)

	if err0 == nil {
		c.Data["json"] = data0
		c.ServeJSON()
		return
	}
	//fmt.Println("new", key)
	symbols := utils.GetSymbolsByConf()

	data := map[string]interface{}{}

	for i := 0; i < len(symbols); i++ {
		data0 := map[string]interface{}{
			"price":     0.0,
			"rise":      0.0,
			"rise_mark": 0,
		}
		price := *new(TypeBuySell)

		price = GetDataFromMydql(symbols[i])

		v := MyRound((price.Buy + price.Sell) / 2)
		data0["price"] = v
		data0["rise"], data0["rise_mark"] = GetRiseBy24H(symbols[i], v, price.Type)

		data[symbols[i]] = data0

	}

	//添加erc20代币价格,涨跌

	//data["UWN"] = GetErc20CoinRise("UWN")

	utils.SetRedisBuyKey("v2"+key, data)

	c.Data["json"] = data
	c.ServeJSON()
}

//func GetErc20CoinRise(coin string) map[string]interface{} {
//	data := map[string]interface{}{
//		"price":     0.0,
//		"rise":      0.0,
//		"rise_mark": 0,
//	}

//	data0 := models.GetErc20coin(coin)
//	if data0.Rise >= 0 {
//		data["rise_mark"] = 1
//		data["rise"] = data0.Rise
//	} else {
//		data["rise_mark"] = 0
//		data["rise"] = data0.Rise
//	}
//	data["price"] = data0.Price
//	return data

//}

func MyRound(v1 float64) float64 {
	v2, _ := strconv.ParseFloat(strconv.FormatFloat(v1, 'f', 2, 64), 64)
	return v2
}

func (c *GetV3PriceController) Get() {
	key := "price"

	symbol := strings.ToUpper(c.GetString(":id"))

	if symbol == "BTC" || symbol == "ETH" || symbol == "LTC" || symbol == "URMB" {
		key = symbol
	} else if symbol != "" {
		data1 := map[string]interface{}{
			"Code": 1,
			"Data": "",
			"Msg":  "币种信息不存在",
		}
		c.Data["json"] = data1
		c.ServeJSON()
	}
	data10, err0 := utils.GetRedisByKey("v3" + key)

	if err0 == nil {
		c.Data["json"] = data10
		c.ServeJSON()
		return
	}
	//fmt.Println("new", key)

	data := map[string]interface{}{
		"Code": 0,
		"Data": "",
		"Msg":  "",
	}
	data0 := map[string]interface{}{}

	if symbol == "BTC" || symbol == "ETH" || symbol == "LTC" || symbol == "URMB" {
		price := GetDataFromMydql(symbol)

		data0[symbol] = price

	} else {
		symbols := utils.GetSymbolsByConf()

		for _, v := range symbols {
			price := GetDataFromMydql(v)

			data0[v] = price
		}

	}
	beego.Debug(data0)
	data["Data"] = data0
	utils.SetRedisBuyKey("v3"+key, data)

	c.Data["json"] = data
	c.ServeJSON()
}

func (c *GetV3CoinriseController) Get() {
	key := "coinrise"
	data0, err0 := utils.GetRedisByKey("v3" + key)
	//fmt.Println(data0, err0)

	if err0 == nil {
		c.Data["json"] = data0
		c.ServeJSON()
		return
	}
	//fmt.Println("new", key)
	symbols := utils.GetSymbolsByConf()

	data := map[string]interface{}{}

	for i := 0; i < len(symbols); i++ {
		data0 := map[string]interface{}{
			"price":     0.0,
			"rise":      0.0,
			"rise_mark": 0,
		}
		price := *new(TypeBuySell)
		price = GetDataFromMydql(symbols[i])
		var v float64
		if symbols[i] != "URMB" {
			v = MyRound((price.Buy + price.Sell) / 2)
		} else {
			v = MyRound((price.Buy + price.Sell) / 2)
		}

		data0["price"] = v
		data0["rise"], data0["rise_mark"] = GetRiseBy24H(symbols[i], v, price.Type)
		data[symbols[i]] = data0
	}

	//添加erc20代币价格,涨跌
	//	Uwncoinrise := GetErc20CoinRise("UWN")
	//	Uwncoinrise["price"] = MyRound(Uwncoinrise["price"].(float64) / priceURMB.Buy)
	//	data["UWN"] = Uwncoinrise

	utils.SetRedisBuyKey("v3"+key, data)

	c.Data["json"] = data
	c.ServeJSON()
}
